using System;
using System.Runtime.Serialization;
using AxeFrog.Data;

namespace AxeFrog.Security
{
	public class User : INamedIdentifiable<long>
	{
		[IdentityField] public long ID { get; set; }
		[Field(0)] public string Name { get; set; }
		[Field] public string Email { get; set; }
		[Field] public string Username { get; set; }
		[Field] public string Password { get; set; }
		[Field] public bool Deleted { get; set; }
		[Field] public int TimeZoneOffsetHours { get; set; }
		[Field] public DateTime DateCreated { get; set; }
		[Field] public DateTime? DateDeleted { get; set; }

		private const string Salt = "$a,pinch_of^salt!";
		public void SetPassword(string plainTextPassword, string publicKey)
		{
			Password = new Encryption().EncryptText(Salt + plainTextPassword, publicKey);
		}

		public bool VerifyPassword(string encryptedPassword, string privateKey)
		{
			if(encryptedPassword == Password)
				return true;
			var enc = new Encryption();
			var pw = enc.DecryptText(Password, privateKey);
			if(pw.Length <= Salt.Length)
				return false;
			return enc.DecryptText(encryptedPassword, privateKey) == enc.DecryptText(Password, privateKey).Substring(Salt.Length);
		}

		public bool IsPasswordCorrect(string password, string privateKey)
		{
			return DecryptPassword(privateKey) == password;
		}

		public string DecryptPassword(string privateKey)
		{
			return new Encryption().DecryptText(Password, privateKey).Substring(Salt.Length);
		}
	}
}